﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;

namespace Luka.Log;

/// <summary>
/// 私有全局类
/// </summary>
internal static class InternalApp
{
    /// <summary>
    /// 配置项
    /// </summary>
    internal static IConfiguration Configuration { get; set; }

    /// <summary>
    /// 根服务
    /// </summary>
    internal static IServiceProvider Providers { get; set; }

    /// <summary>
    /// 获取Web主机环境
    /// </summary>
    internal static IHostingEnvironment HostEnvironment { get; set; }

    /// <summary>
    /// 当前程序集名称
    /// </summary>
    internal static string ProgramName => AppDomain.CurrentDomain.FriendlyName;

    /// <summary>
    /// 用户信息
    /// </summary>
    internal static string UserInfo
    {
        get
        {
            // 获取ILogHandle服务
            var _handle = GetService<ILogHandle>();
            // 如果服务不为空
            if (_handle != null)
            {
                // 获取用户信息
                var user = _handle.SetUserInfo();
                // 如果用户信息不为空
                if (user != null)
                {
                    // 将用户信息序列化为Json字符串
                    return JsonConvert.SerializeObject(user);
                }
            }
            return default;
        }
    }

    /// <summary>
    /// 获取配置文件中SkeygeoLog节点的LogOptions配置
    /// </summary>
    internal static LogOptions LogOptions => Configuration.GetSection("SkygeoLog").Get<LogOptions>();

    /// <summary>
    /// 当前环境名称
    /// </summary>
    internal static string EnvironmentName => Environment.GetEnvironmentVariables()["ASPNETCORE_ENVIRONMENT"]?.ToString() ?? "";

    /// <summary>
    ///  获取服务
    /// </summary>
    /// <typeparam name="TService">服务类型</typeparam>
    /// <returns></returns>
    internal static TService GetService<TService>() where TService : class => Providers.GetService<TService>();

    /// <summary>
    /// 获取config文件信息
    /// </summary>
    /// <param name="key">键名</param>
    /// <returns></returns>
    internal static string GetSection(string key)
    {
        if (string.IsNullOrWhiteSpace(key))
            return default;
        return Configuration.GetValue<string>(key) ?? string.Empty;
    }

    /// <summary>
    /// 获取config文件信息
    /// </summary>
    /// <typeparam name="TOptions">泛型类型</typeparam>
    /// <param name="key">键名</param>
    /// <returns></returns>
    internal static TOptions GetSection<TOptions>(string key) where TOptions : class, new()
    {
        if (string.IsNullOrWhiteSpace(key))
            return default;
        return Configuration.GetSection(key).Get<TOptions>() ?? new TOptions();
    }
}